package com.panfeng.xcloud.common.core.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;

public class IpUtil {
	
	/**
	 * 获取IP地址
	 * 
	 * @param request
	 * @return
	 */
	public static String getClientIp(HttpServletRequest request) {
		if(null == request){
			return "";
		}
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	/**
	 * 获取当前服务器ip地址
	 * 
	 * @return
	 */
	public static InetAddress getCurrentIpForInetAddress() {
		try {
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
					.getNetworkInterfaces();
			while (networkInterfaces.hasMoreElements()) {
				NetworkInterface ni = networkInterfaces
						.nextElement();
				Enumeration<InetAddress> nias = ni.getInetAddresses();
				while (nias.hasMoreElements()) {
					InetAddress ia = nias.nextElement();
					if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress()
							&& ia instanceof Inet4Address) {
						return ia;
					}
				}
			}
		} catch (SocketException e) {
		}
		return null;
	}

	/**
	 * 获取当前服务器ip地址
	 * 
	 * @return
	 */
	public static String getCurrentIp() {
		InetAddress inetAddress = getCurrentIpForInetAddress();
		if (null != inetAddress) {
			return inetAddress.getHostAddress();
		}
		return "127.0.0.1";
	}

	/**
	 * 测试主机host的port端口是否被使用
	 * 
	 * @param host
	 * @param port
	 * @return
	 */
	public static boolean isPortUsing(String host, int port) {
		boolean isUsing = false;
		Socket socket = null;
		if (port <= 0 || port > 65535)
			throw new IllegalArgumentException("parameter bind error port :" + port);
		try {
			InetAddress address = InetAddress.getByName(host);
			socket = new Socket(address, port);
			isUsing = true;
		} catch (Exception e) {
		} finally {
			if (null != socket) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return isUsing;
	}

	public static void main(String[] args) {
		System.out.println(getCurrentIp());
		System.out.println(isPortUsing(getCurrentIp(),20880)?"被占用":"未被占用");
	}

}
